import { constant } from '@/utils/constant.js'

const send = (url, data = {}, method = 'POST', showLoading = true) => {
    uni.showLoading({
        title: '加载中'
    })
    return new Promise((resolve, reject) => {
        uni.request({
            method: method,
            url: url,
            data: data,
            header: (() => {
				let config = {
					'Content-Type': 'application/json'
				}
				let token = uni.getStorageSync(constant.tokenKey)
                if (token) {
                    config[constant.tokenKey] = token
                }
                return config
            })(),
            success: (res) => {
                uni.hideLoading()
				if (res.data.code !== 200) {
					if(res.data.code === 401) {
						uni.removeStorageSync(constant.tokenKey)
						uni.removeStorageSync(constant.userInfo)
						uni.showModal({
							title: '温馨提示',
							content: res.data.msg || "您还未登录，请先登录",
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/login/login'
									})
								} else {
									uni.navigateBack({
										delta: 1,
										fail: (res) => {
											uni.switchTab({
												url: '/pages/index/index',
											})
										}
									})
								}
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon:"none"
						})
					}
				} else {
					resolve(res.data)
				}
            },
			fail: (err)=>{
				uni.showToast({
					icon: 'none',
					title: '请求接口失败'
				})
				reject(err)
			}
        })
    })
}

export const request = {
    get: (url, data) => {
        return send(url, data, 'GET')
    },
    post: (url, data) => {
        return send(url, data, 'POST')
    },
	put: (url, data) => {
	    return send(url, data, 'PUT')
	},
	delete: (url, data) => {
	    return send(url, data, 'DELETE')
	}
}